package Servlet;

import dao.UserDao;
import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/zhuce")
public class RegisterServlet extends HttpServlet {
    private UserDao userDao = new UserDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String confirmPassword = req.getParameter("confirmPassword");

        // 验证密码是否匹配
        if (!password.equals(confirmPassword)) {
            req.setAttribute("error", "两次输入的密码不一致，请重新输入。");
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
            return;
        }

        // 创建用户对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password); // 注意：在实际应用中，密码应该被加密存储

        // 调用DAO方法保存用户到数据库
        boolean result = userDao.addUser(user);

        // 根据结果设置响应
        if (result) {
            resp.sendRedirect("index.jsp?success=t"); // 注册成功，重定向到登录页面
        } else {
            req.setAttribute("error", "注册失败，用户名可能已存在。");
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 对于注册页面，我们通常只处理POST请求，GET请求可以重定向到注册页面
        resp.sendRedirect("register.jsp");
    }
}